package org.zn.mvcbase.exception;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.server.ServletServerHttpRequest;

/**
 * @ProjectName:zqdk-mvcbase
 * @Description: 
 * @author: 周楠
 * @date 2017年3月6日 上午10:53:17
 */

public class ExceptionResponseStateFactory {

    private List<ExceptionResponseRegister> registry;
    
    public List<ExceptionResponseRegister> getRegistry() {
		return registry;
	}

	public void setRegistry(List<ExceptionResponseRegister> registry) {
		this.registry = registry;
	}

	public void registrySort(){
   
    	Collections.sort(registry);
    	
    }
	
	@PostConstruct
	public void init(){
		
	List<ExceptionResponseRegister>	baseRegistry =new ArrayList<>();

	baseRegistry.add(new AjaxExceptionResponseRegister());
	baseRegistry.add(new DirectResponseRegister());

	if(registry!=null){
	baseRegistry.addAll(registry);
	}	
	registry=baseRegistry;
	
	registrySort();
	}
	
    
    private  Class<? extends ExceptionResponseState> findInRegistry(HttpInputMessage httpInputMessage){
    	
    	Class<? extends ExceptionResponseState> stateclazz=null;
    	
    	for (ExceptionResponseRegister reg : registry) {
			
          stateclazz=reg.getExceptionResponseStateType(httpInputMessage);

    		if(stateclazz!=null){
    			break;
    		}
    		
		}
		return stateclazz;
    
    }

	
	public ExceptionResponseState getExceptionResponseState(HttpServletRequest request){
		
		HttpInputMessage inputMessage= new ServletServerHttpRequest(request);  
		
		 Class<? extends ExceptionResponseState> clazz=findInRegistry(inputMessage);
		 ExceptionResponseState ers=null;
		 try {
			 ers= clazz.newInstance();

		 } catch (InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		return ers;
		
	}
	
	
	
	
	
	
	
}
